import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ArticleService } from '@/services/articleService'
import { logger } from '@/utils/logger'
import { useAppStore } from './app'

const articleService = new ArticleService()

export const useFavoritesStore = defineStore('favorites', () => {
  const appStore = useAppStore()
  
  // 状态
  const favorites = ref([])
  const loading = ref(false)
  const error = ref(null)
  const searchQuery = ref('')
  const selectedItems = ref(new Set())
  const pagination = ref({
    page: 1,
    per_page: 20,
    total: 0,
    pages: 0
  })
  
  // 计算属性
  const filteredFavorites = computed(() => {
    if (!searchQuery.value.trim()) {
      return favorites.value
    }
    
    const query = searchQuery.value.toLowerCase()
    return favorites.value.filter(fav => 
      fav.article_number.toLowerCase().includes(query) ||
      fav.title.toLowerCase().includes(query)
    )
  })
  
  const hasSelectedItems = computed(() => selectedItems.value.size > 0)
  const allItemsSelected = computed(() => 
    filteredFavorites.value.length > 0 && 
    filteredFavorites.value.every(fav => selectedItems.value.has(fav.article_number))
  )
  
  const favoritesCount = computed(() => favorites.value.length)
  const isEmpty = computed(() => favorites.value.length === 0 && !loading.value)
  
  // 收藏统计
  const favoriteStats = computed(() => {
    const stats = {
      totalCount: favorites.value.length,
      byPart: {},
      recentCount: 0
    }
    
    // 按编统计
    favorites.value.forEach(fav => {
      if (fav.part) {
        stats.byPart[fav.part] = (stats.byPart[fav.part] || 0) + 1
      }
      
      // 最近7天收藏
      const createdAt = new Date(fav.created_at)
      const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
      if (createdAt > sevenDaysAgo) {
        stats.recentCount++
      }
    })
    
    return stats
  })
  
  // 操作方法
  async function loadFavorites(page = 1) {
    try {
      loading.value = true
      error.value = null
      
      const result = await articleService.getFavorites({
        page,
        per_page: pagination.value.per_page
      })
      
      console.log('[FavoritesStore] API 返回结果:', result)
      favorites.value = result.favorites || []
      pagination.value = {
        ...pagination.value,
        ...result.pagination,
        page
      }
      console.log('[FavoritesStore] 加载后的收藏列表:', favorites.value)
      
      logger.userAction('加载收藏列表', { 
        page, 
        count: favorites.value.length 
      })
      
    } catch (err) {
      error.value = err.message
      appStore.setError(`加载收藏列表失败: ${err.message}`)
      logger.error('加载收藏列表失败:', err)
    } finally {
      loading.value = false
    }
  }
  
  async function removeFavorite(articleNumber) {
    try {
      await articleService.removeFavorite(articleNumber)
      
      // 从列表中移除
      const index = favorites.value.findIndex(fav => fav.article_number === articleNumber)
      if (index > -1) {
        favorites.value.splice(index, 1)
        
        // 更新分页信息
        pagination.value.total = Math.max(0, pagination.value.total - 1)
        
        // 从选中项中移除
        selectedItems.value.delete(articleNumber)
      }
      
      appStore.addNotification({ type: 'success', message: '已取消收藏' })
      logger.userAction('取消收藏', { articleNumber })
      
    } catch (err) {
      appStore.setError(`取消收藏失败: ${err.message}`)
      logger.error('取消收藏失败:', err)
      throw err
    }
  }
  
  async function batchRemoveFavorites() {
    if (selectedItems.value.size === 0) return
    
    try {
      loading.value = true
      const articleNumbers = Array.from(selectedItems.value)
      
      // 批量删除
      await Promise.all(
        articleNumbers.map(articleNumber => 
          articleService.removeFavorite(articleNumber)
        )
      )
      
      // 从列表中移除
      favorites.value = favorites.value.filter(fav => 
        !selectedItems.value.has(fav.article_number)
      )
      
      // 更新分页信息
      pagination.value.total = Math.max(0, pagination.value.total - selectedItems.value.size)
      
      // 清空选中项
      selectedItems.value.clear()
      
      appStore.addNotification({ type: 'success', message: `已批量取消 ${articleNumbers.length} 个收藏` })
      logger.userAction('批量取消收藏', { count: articleNumbers.length })
      
    } catch (err) {
      appStore.setError(`批量取消收藏失败: ${err.message}`)
      logger.error('批量取消收藏失败:', err)
    } finally {
      loading.value = false
    }
  }
  
  function toggleSelectItem(articleNumber) {
    if (selectedItems.value.has(articleNumber)) {
      selectedItems.value.delete(articleNumber)
    } else {
      selectedItems.value.add(articleNumber)
    }
  }
  
  function toggleSelectAll() {
    if (allItemsSelected.value) {
      // 取消全选
      filteredFavorites.value.forEach(fav => {
        selectedItems.value.delete(fav.article_number)
      })
    } else {
      // 全选
      filteredFavorites.value.forEach(fav => {
        selectedItems.value.add(fav.article_number)
      })
    }
  }
  
  function clearSelection() {
    selectedItems.value.clear()
  }
  
  function setSearchQuery(query) {
    searchQuery.value = query
  }
  
  function exportFavorites() {
    try {
      const data = favorites.value.map(fav => ({
        '条文编号': fav.article_number,
        '条文标题': fav.title,
        '所属编': fav.part || '未知',
        '收藏时间': new Date(fav.created_at).toLocaleString('zh-CN')
      }))
      
      const csv = [
        Object.keys(data[0]).join(','),
        ...data.map(row => Object.values(row).join(','))
      ].join('\n')
      
      const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = `民法典收藏列表_${new Date().toISOString().split('T')[0]}.csv`
      link.click()
      
      appStore.addNotification({ type: 'success', message: '收藏列表已导出' })
      logger.userAction('导出收藏列表', { count: favorites.value.length })
      
    } catch (err) {
      appStore.setError(`导出失败: ${err.message}`)
      logger.error('导出收藏列表失败:', err)
    }
  }
  
  function reset() {
    favorites.value = []
    loading.value = false
    error.value = null
    searchQuery.value = ''
    selectedItems.value.clear()
    pagination.value = {
      page: 1,
      per_page: 20,
      total: 0,
      pages: 0
    }
  }
  
  return {
    // 状态
    favorites,
    loading,
    error,
    searchQuery,
    selectedItems,
    pagination,
    
    // 计算属性
    filteredFavorites,
    hasSelectedItems,
    allItemsSelected,
    favoritesCount,
    isEmpty,
    favoriteStats,
    
    // 方法
    loadFavorites,
    removeFavorite,
    batchRemoveFavorites,
    toggleSelectItem,
    toggleSelectAll,
    clearSelection,
    setSearchQuery,
    exportFavorites,
    reset
  }
})
